﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MotionControl.Modules.RestService.Controllers
{
    public class WebSocketConnections
    {
        private readonly List<WebSocket> _connections = new List<WebSocket>();

        public void Add(WebSocket webSocket)
        {
            _connections.Add(webSocket);
        }

        public void Remove(WebSocket webSocket)
        {
            _connections.Remove(webSocket);
        }

        public async Task SendToAll(string message)
        {
            var buffer = Encoding.UTF8.GetBytes(message);
            foreach (var connection in _connections)
            {
                await connection.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
    }
}
